import re

import pymysql


class Camel:
    def __init__(self, connect=None) -> None:
        if (connect == None):
            return
        self.connect = self.get_connect_cur(connect)
        self.cur = self.connect.cursor()

    def sqltocamel(s):
        s = re.sub(r"(\s|_|-)+", " ", s).title().replace(" ", "")
        return s[0].lower() + s[1:]

    # 批量转化
    def batch_camel(self, slist):
        return [self.sqltocamel(s) for s in slist]


    # business_date, realdeal_serial_no, company_id, fund_id, asset_id, combi_id, capital_account_id, entrust_serial_no, batch_serial_no, invest_type, market_no, stockholder_id, trade_seat, report_code, report_serial_no, deal_time, deal_amount, deal_price, deal_no, option_covered_flag, trade_platform_id, entrust_direction, clear_speed, operator_no, instance_id, cashgroup_prop
    # 处理成xml的insert语句
    def insert_xml(self, strs):
        prostr = self.enter_str(strs)
        result = "(" + prostr + "\n)" + " values " + "("
        strs = self.camel_str(strs)
        tag = True
        for str in strs:
            if (tag):
                result = result + "\n#{" + str + "}"
                tag = False
            else:
                result = result + "," + "\n#{" + str + "}"
        return result + ")"

    # 批处理成驼峰结构
    def camel_str(self, strs):
        return self.batch_camel(self, strs.split(','))

    # 给源字符串添加换行
    def enter_str(strs):
        result = ''
        tag = True
        for str in strs.split(','):
            if (tag):
                result = result + str
                tag = False
            else:
                result = result + ",\n" + str
        return result

    # 处理成实体类形式
    def sql_to_entry(self, strs):
        result = ""
        for str in self.camel_str(strs):
            result += "private"

    # 获取mysql连接
    def get_connect_cur(connect, table_name, charaSet="gbk"):
        conn = pymysql.connect(port=connect.get("port"),
                               host=connect.get("host"),
                               password=connect.get("password"),
                               user=connect.get("password"),
                               db=connect.get("db"),
                               charset=charaSet
                               )
        return conn

    # 获取
    def get_table_field_info(self, table_name):
        sqllist = 'desc %s;' % (table_name)
        self.cur.execute(sqllist)
        result = self.cur.fetchall()
        td = [
            {
                'Field': i[0],
                'Type': i[1],
                'Null': i[2],
                'Key': i[3],
                'Default': i[4]
            } for i in result
        ]
        return td

    def get_table_field(connect, db, table_name, charaSet="gbk"):
        conn = pymysql.connect(port=connect.get("port"),
                               host=connect.get("host"),
                               password=connect.get("password"),
                               user=connect.get("password"),
                               db=db,
                               charset=charaSet
                               )
        cur = conn.cursor()
        sqllist = 'desc %s.%s;' % (db, table_name)
        cur.execute(sqllist)
        result = cur.fetchall()
        td = [
            {
                'Field': i[0],
                'Type': i[1],
                'Null': i[2],
                'Key': i[3],
                'Default': i[4]
            } for i in result
        ]
        return td

    # 驼峰转下划线
    def uncamelize(cls, camelCaps, separator="_"):
        pattern = re.compile(r'([A-Z]{1})')
        sub = re.sub(pattern, separator + r'\1', camelCaps).lower()
        return sub

    def batch_uncamelize(self, strs):
        return [self.uncamelize(str) for str in strs]

    # java驼峰转下划线
    def cameltosql(self, str):
        result = ""
        camelstrs = self.javatostr(str)
        sqlstrs = self.batch_uncamelize(camelstrs)
        for str in sqlstrs:
            result += ",\n" + str
        for str in camelstrs:
            result += ",\n" + "#{param1." + str + "}"
        return result

    # 解析java代码
    def javatostr(self, str):
        result = []
        for i in str.split(";"):
            if (len(i.split(" ")[-1]) > 0):
                result.append(i.split(" ")[-1])
        return result
